﻿using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Presentation;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business.CommonReportConfigs;
using NP.BPMReportPlatform.Reports.CommonReportConfigs.Dtos;
using NRules;
using NRules.Fluent;
using NRules.Fluent.Dsl;
using NRules.RuleModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NP.BPMReportPlatform.Reports.CommonReportConfigs
{
    public class CommonReportRuleService : BPMReportPlatformAppService, ICommonReportRuleService
    {
        private readonly SqlSugarClient _db;
        private readonly IRuleRepository _ruleRepository;

        public CommonReportRuleService(ISqlSugarAppService sqlSugarAppService, IRuleRepository ruleRepository)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _ruleRepository = ruleRepository;
        }

        public async Task<List<CommonReportRules>> GetRuleList(List<string> ruleIds)
        {
            var rules = await _db.Queryable<CommonReportRules>().Where(x => SqlFunc.ContainsArray(ruleIds, x.Id)).ToListAsync();
            var conditions = await _db.Queryable<CommonReportConditions>().Where(x => SqlFunc.ContainsArray(ruleIds, x.RuleId)).ToListAsync();
            rules.ForEach(x => x.ConditionList = conditions.Where(q => q.RuleId == x.Id).ToList());

            return rules;
        }

        public void RuleExecute(RuleExecuteInput input)
        {
            //Load rules
            var repository = new RuleRepository();
            repository.Load(x => x.From(typeof(DynamicRule).Assembly));

            //Compile rules
            var factory = repository.Compile();

            //Create a working session
            var session = factory.CreateSession();

            //Insert facts into rules engine's memory
            session.Insert(input);

            //Start match/resolve/act cycle
            session.Fire();
        }
    }
}
